<template>
  <el-card>
    <el-form inline class="category-selector-form">
      <el-form-item label="一级分类">
        <el-select placeholder="请选择" v-model="categoryStore.category1Id">
          <el-option
            v-for="c1 in categoryStore.category1List"
            :key="c1.id"
            :label="c1.name"
            :value="c1.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="二级分类">
        <el-select placeholder="请选择" v-model="categoryStore.category2Id">
          <el-option
            v-for="c2 in categoryStore.category2List"
            :key="c2.id"
            :label="c2.name"
            :value="c2.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="三级分类">
        <el-select placeholder="请选择" v-model="categoryStore.category3Id">
          <el-option
            v-for="c3 in categoryStore.category3List"
            :key="c3.id"
            :label="c3.name"
            :value="c3.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "CategorySelector",
};
</script>

<script lang="ts" setup>
import { useCategoryStore } from "@/stores/category";
import { onMounted, watch, onBeforeUnmount } from "vue";

const categoryStore = useCategoryStore();
//一挂载时就要获取一级分类列表
onMounted(() => {
  categoryStore.getCategory1List();
});

// 卸载组件 重置初始值
onBeforeUnmount(() => {
  categoryStore.$reset();
});

watch(
  () => categoryStore.category1Id,
  (newVal) => {
    categoryStore.getCategory2List(newVal as number);
  }
);
watch(
  () => categoryStore.category2Id,
  (newVal) => {
    if (!newVal) return;
    categoryStore.getCategory3List(newVal as number);
  }
);
</script>

<style scoped>
.category-selector-form :deep(.el-form-item) {
  margin-top: 10px;
  margin-bottom: 10px;
}
</style>
